<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\AliyunUtil;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 用户私人资料表
 */
class UserProfilePersonal extends Model
{
    protected $table = 'user_profile_personal';

    //待审核
    const STATUS_ING = 0;
    //审核通过
    const STATUS_OK = 1;
    //审核不通过
    const STATUS_FAIL = 2;

    //支付宝
    const BIND_TYPE_ALI = 1;
    //银行卡
    const BIND_TYPE_BANK = 2;

    /**
     * 更新私人资料
     */
    static function updateInfo($userId = 0, $info = [])
    {
        $model = self::where('user_id', $userId)->first();
        if (!$model) $model = new self();
        $model->user_id = $userId;
        isset($info['real_name']) && $model->real_name = $info['real_name'];
        isset($info['id_card']) && $model->id_card = $info['id_card'];
        isset($info['bank_card']) && $model->bank_card = $info['bank_card'];
        isset($info['id_card_pics']) && $model->id_card_pics =  $info['id_card_pics'];
        isset($info['phone']) && $model->phone =  $info['phone'];
        if (isset($info['real_name']) || isset($info['id_card_pics']) || isset($info['id_card'])) {
            $model->flag = self::STATUS_ING;
        }
        // $model->flag = self::STATUS_ING;
        isset($info['alipay_account']) && $model->alipay_account = $info['alipay_account'];
        isset($info['vry_type']) && $model->vry_type = $info['vry_type'];
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 解绑收款账号
     */
    static function clearAccount($userId = 0, $accountType = '')
    {
        $model = self::where('user_id', $userId)->first();
        if (!$model) $model = new self();
        (!$accountType || $accountType == 'alipay') && $model->alipay_account = '';
        (!$accountType || $accountType == 'bank') && $model->bank_card = '';
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 获取个人资料
     */
    static function getProfile($userId = 0)
    {
        if (!$userId) return [];
        $where = ['user_id' => $userId]; //, 'flag' => self::STATUS_OK
        $item = self::where($where)->first();
        $data = $item ? $item->toArray() : [];
        if ($data && $data['id_card_pics']) {
            $data['id_card_pics'] = json_decode($data['id_card_pics'], true);
            foreach ($data['id_card_pics'] as &$pic) $pic = AliyunUtil::IMG_HOST . $pic;
        }
        return $data;
    }

    /**
     * 是否已经姓名身份认证
     */
    static function isRealnameVerified($personInfo = [])
    {
        if (!$personInfo) return 0;
        // if (!is_array($personInfo)) $personInfo = $personInfo->toArray();
        return $personInfo['real_name'] ? 1 : 0;
    }

    /**
     * 是否已经刷脸认证
     */
    static function isFaceVerified($personInfo = [])
    {
        if (!$personInfo) return 0;
        // if (!is_array($personInfo)) $personInfo = $personInfo->toArray();
        return $personInfo['real_name'] && $personInfo['flag'] == self::STATUS_OK ? 1 : 0;
    }

    /**
     * 是否绑定收款账号
     */
    static function isBindAccount($personInfo = null)
    {
        return $personInfo['alipay_account'] || $personInfo['bank_card'];
    }

    /**
     * 保存实名认证信息
     */
    static function saveRealnameInfo($userId = 0, $realName = '', $idNo = '')
    {
        if (!$userId || !$realName || !$idNo) return false;
        $model = self::where('user_id', $userId)->first();
        if (!$model) $model = new self();
        $model->user_id = $userId;
        $model->real_name = $realName;
        $model->id_card = $idNo;
        $model->flag = self::STATUS_ING;
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 查找身份证信息是否存在
     */
    static function checkIdCard($idNo = '')
    {
        if (!$idNo) return false;
        $where = [
            'id_card' => $idNo,
            'flag' => self::STATUS_OK
        ];
        return self::where($where)->exists();
    }

    /**
     * 审核状态
     */
    static function vrfyStatus($userId = 0, $status = self::STATUS_OK, $facePic = '', $vrfyInfo = null)
    {
        $model = self::where('user_id', $userId)->first();
        if (!$model) $model = new self();
        $model->user_id = $userId;
        $status > -1 && $model->flag = $status;
        $facePic && $model->face_vry_pic = $facePic;
        $vrfyInfo && $model->vry_detail = is_string($vrfyInfo) ? $vrfyInfo : json_encode($vrfyInfo);
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 更新认证业务ID
     */
    static function updateBizNo($userId = 0, $bizNo = '', $vrfyType = 1)
    {
        if ($vrfyType == 1) $field = 'biz_no_real';
        elseif ($vrfyType == 2) $field = 'biz_no_avatar';
        else return false;
        $model = self::where('user_id', $userId)->first();
        if (!$model) return false;
        $model->{$field} = $bizNo;
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 与真人照片对比
     */
    static function compareRealFacepic($userId = 0, $avatar = '')
    {
        if (!$avatar || !$userId) return 0;
        $info = self::where('user_id', $userId)->first();
        if (!$info || !$info->face_vry_pic) return 0;
        $avatar = UserProfile::buildAvatar($avatar, 300, 300);
        $facePic = AliyunUtil::IMG_HOST . $info->face_vry_pic;
        return  AliyunUtil::compareFaces([$avatar, $facePic], $userId);
    }

    /**
     * 是否在审核中
     */
    static function checkVerifing($userId = 0, $info = null)
    {
        !$info && $info = self::where('user_id', $userId)->first();
        if (!$info) return 0;
        !is_array($info) && $info = $info->toArray();
        return $info['flag'] == self::STATUS_ING ? 1 : 0;
    }

    /**
     * 获取绑定提现信息
     */
    static function getBindInfo($userId = 0, $type = 'alipay')
    {
        $info = self::where('user_id', $userId)->first();
        if (!$info || $info->flag != self::STATUS_OK) return [];

        if ($info->alipay_account && in_array($type, ['alipay', ''])) {
            return [
                'real_name' => $info->real_name,
                'id_card' => $info->id_card,
                'card_no' => $info->alipay_account,
                'type' => self::BIND_TYPE_ALI
            ];
        }
        if ($info->bank_card && in_array($type, ['bank', ''])) {
            return [
                'real_name' => $info->real_name,
                'id_card' => $info->id_card,
                'card_no' => $info->bank_card,
                'type' => self::BIND_TYPE_BANK
            ];
        }
        return [];
    }

    /**
     * 实名认证人数
     * @param $startTime
     * @param $endTime
     * @param $channel
     * @return int
     */
    static function getRealNameTotalByDay($startTime, $endTime, $channel)
    {
        $where = [
            ['user_profile_personal.real_name', '<>', ''],
            ['user_profile_personal.flag', '=', self::STATUS_OK]
        ];

        if ($startTime) $where[] = ['user_profile_personal.created_at', '>=', $startTime];
        if ($endTime) $where[] = ['user_profile_personal.created_at', '<', $endTime];

        if (!$channel) {
            $query = self::where($where);
        } else {
            $query = Db::table('user_profile_personal')->join('user', function ($join) use ($where, $channel) {
                $where[] = ['channel', $channel];
                $join->on('user.id', '=', 'user_profile_personal.user_id')->where($where);
            });
        }

        log_info($query->toSql());

        return $query->count();
    }
}
